<template>
  <div style="height: 100%; width: 100%">
    <!-- 查询框 -->
    <div>
      <el-select v-model="searchType" placeholder="请选择查询条件" style="width: 150px;">
        <el-option label="序号" value="id"></el-option>
        <el-option label="医生姓名" value="name"></el-option>
      </el-select>
      <el-input v-model="keyword" style="width: 300px; margin-left: 10px; margin-right: 10px" placeholder="请输入关键词"></el-input>
      <el-button type="primary" @click="search">查询</el-button>
      <el-button type="info" @click="reset">重置</el-button>
    </div>
    <!-- 操作框 -->
    <div style="margin: 10px 0">
      <el-button type="primary" plain @click="showAddDialog">新增</el-button>
      <el-button type="danger" plain @click="delBatch">批量删除</el-button>
    </div>
    <!-- 表格 -->
    <div>
      <el-table :data="doctors" stripe :header-cell-style="{ backgroundColor: 'aliceblue', color: '#666' }"
                @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center"></el-table-column>
        <el-table-column prop="id" label="序号" width="70" align="center"></el-table-column>
        <el-table-column prop="doctor_name" label="医生姓名"></el-table-column>
        <el-table-column prop="schedule_date" label="排班日期"></el-table-column>
        <el-table-column prop="start_time" label="开始时间"></el-table-column>
        <el-table-column prop="end_time" label="结束时间"></el-table-column>
        <el-table-column prop="status" label="状态"></el-table-column>
        <el-table-column label="操作" align="center" width="180">
          <template slot-scope="scope">
            <el-button size="mini" type="primary" plain @click="handleEdit(scope.row)">编辑</el-button>
            <el-button size="mini" type="danger" plain @click="handleDelete(scope.row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 分页组件 -->
    <div style="margin-top: 20px; text-align: center;">
      <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-sizes="[5, 10, 20, 50]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="totalItems">
      </el-pagination>
    </div>
    <!-- 新增/编辑弹窗 -->
    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="30%">
      <el-form ref="form" :model="editItem" label-width="80px">
        <el-form-item label="医生姓名" prop="doctor_name">
          <el-input v-model="editItem.doctor_name"></el-input>
        </el-form-item>
        <el-form-item label="排班日期" prop="schedule_date">
          <el-date-picker v-model="editItem.schedule_date" type="date" placeholder="选择日期" value-format="yyyy-MM-dd"></el-date-picker>
        </el-form-item>
        <el-form-item label="开始时间" prop="start_time">
          <el-time-picker v-model="editItem.start_time" placeholder="选择时间" value-format="HH:mm:ss"></el-time-picker>
        </el-form-item>
        <el-form-item label="结束时间" prop="end_time">
          <el-time-picker v-model="editItem.end_time" placeholder="选择时间" value-format="HH:mm:ss"></el-time-picker>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-input v-model="editItem.status"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="closeDialog">取消</el-button>
        <el-button type="primary" @click="handleSaveEdit">{{ isEditing ? '保存' : '新增' }}</el-button>
      </span>
    </el-dialog>
    <!-- 排班图表 -->
    <div id="schedule-chart" style="width: 100%; height: 400px; margin-top: 20px;"></div>
  </div>
</template>

<script>
import axios from 'axios';
import * as echarts from 'echarts';

export default {
  name: 'DoctorView',
  data() {
    return {
      doctors: [],
      selectedRows: [],
      currentPage: 1,
      pageSize: 5,
      totalItems: 0,
      searchType: 'id',
      keyword: '',
      dialogVisible: false,
      editItem: {
        doctor_name: '',
        schedule_date: '',
        start_time: '',
        end_time: '',
        status: ''
      },
      isEditing: false
    };
  },
  computed: {
    dialogTitle() {
      return this.isEditing ? '编辑医生信息' : '新增医生信息';
    }
  },
  mounted() {
    this.search();
  },
  methods: {
    search() {
      let url = 'http://localhost:8080/doctors/selectAll';
      let params = {
        page: this.currentPage,
        size: this.pageSize
      };

      if (this.keyword) {
        url = `http://localhost:8080/doctors/selectBy${this.searchType}?${this.searchType}=${this.keyword}`;
      }

      axios.get(url, { params })
          .then(response => {
            const data = response.data.data;
            this.doctors = data.list;
            this.totalItems = data.total;
            this.renderChart();
          })
          .catch(error => {
            console.error('Error fetching inventory:', error);
          });
    },
    reset() {
      this.searchType = 'id';
      this.keyword = '';
      this.currentPage = 1;
      this.pageSize = 5;
      this.search();
    },
    handleSizeChange(size) {
      this.pageSize = size;
      this.search();
    },
    handleCurrentChange(page) {
      this.currentPage = page;
      this.search();
    },
    handleSelectionChange(val) {
      this.selectedRows = val.map(row => row.id);
    },
    showAddDialog() {
      this.isEditing = false;
      this.dialogVisible = true;
    },
    closeDialog() {
      this.dialogVisible = false;
      this.isEditing = false;
    },
    handleAdd() {
      axios.post("http://localhost:8080/doctors/add", this.editItem)
          .then(response => {
            this.$message.success("新增成功");
            this.dialogVisible = false;
            this.search();
          })
          .catch(error => {
            console.error('Error adding new item:', error);
            this.$message.error("新增失败");
          });
    },
    handleEdit(row) {
      this.editItem = Object.assign({}, row);
      this.isEditing = true;
      this.dialogVisible = true;
    },
    handleSaveEdit() {
      if (this.isEditing) {
        axios.put("http://localhost:8080/doctors/edit", this.editItem)
            .then(response => {
              this.$message.success("编辑成功");
              this.closeDialog();
              this.search();
            })
            .catch(error => {
              console.error('Error editing item:', error);
              this.$message.error("编辑失败");
            });
      } else {
        this.handleAdd();
      }
    },
    handleDelete(id) {
      this.$confirm('此操作将永久删除该条目，是否继续？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        axios.delete(`http://localhost:8080/doctors/delete/${id}`)
            .then(response => {
              this.$message.success('删除成功');
              this.search();
            })
            .catch(error => {
              console.error('Error deleting item:', error);
              this.$message.error('删除失败');
            });
      }).catch(() => {
        this.$message.info('已取消删除');
      });
    },
    delBatch() {
      this.$confirm('此操作将永久删除所选条目，是否继续？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        axios.delete(`http://localhost:8080/doctors/deleteBatch`, { data: this.selectedRows })
            .then(response => {
              this.$message.success('批量删除成功');
              this.search();
              this.selectedRows = [];
            })
            .catch(error => {
              console.error('Error deleting batch:', error);
              this.$message.error('批量删除失败');
            });
      }).catch(() => {
        this.$message.info('已取消批量删除');
      });
    },
    renderChart() {
      const scheduleData = this.formatScheduleData();
      const chartDom = document.getElementById('schedule-chart');
      const myChart = echarts.init(chartDom);
      const option = {
        title: {
          text: '医生排班情况',
          left: 'center'
        },
        tooltip: {
          trigger: 'axis',
          formatter: function (params) {
            let result = params[0].name + '<br/>';
            params.forEach(item => {
              if (item.data && item.data.start_time && item.data.end_time) {
                result += `${item.seriesName}: ${item.data.start_time} - ${item.data.end_time}<br/>`;
              }
            });
            return result;
          }
        },
        legend: {
          data: scheduleData.doctors,
          top: 'bottom'
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '20%', // 增加bottom的值来在图表底部留出更多空间
          containLabel: true
        },
        xAxis: {
          type: 'category',
          boundaryGap: false,
          data: ['周一', '周二', '周三', '周四', '周五', '周六', '周日']
        },
        yAxis: {
          type: 'value',
          min: 0,
          max: 24, // 设置Y轴的最大值为24
          axisLabel: {
            formatter: function (value) {
              // 格式化函数将值转换为小时格式（0-23）
              return value.toFixed(0) + '点'; // 使用toFixed确保显示整数，并添加'点'后缀
            }
          },
          splitLine: {
            show: true // 显示Y轴的分割线
          }
        },
        series: scheduleData.series
      };

      myChart.setOption(option);
    },
    formatScheduleData() {
      const days = ['周一', '周二', '周三', '周四', '周五', '周六', '周日'];
      const seriesData = this.doctors.map(doc => {
        const itemStyle = {
          normal: {
            color: this.getColorForDoctor(doc.doctor_name) // 自定义函数，用于生成颜色
          }
        };
        const data = days.map(day => {
          if (this.isDoctorScheduledOnDay(doc, day)) {
            // 返回包含排班时间段的对象
            return {
              value: 1,
              start_time: doc.start_time,
              end_time: doc.end_time,
              itemStyle
            };
          } else {
            return null;
          }
        });
        return {
          name: doc.doctor_name,
          type: 'bar',
          stack: '排班',
          data
        };
      });
      return {
        doctors: this.doctors.map(doc => doc.doctor_name),
        series: seriesData
      };
    },
    isDoctorScheduledOnDay(doc, day) {
      const scheduleDay = new Date(doc.schedule_date).getDay();
      const dayIndex = ['周日', '周一', '周二', '周三', '周四', '周五', '周六'].indexOf(day);
      return scheduleDay === dayIndex;
    },
    getColorForDoctor(doctorName) {
      const colors = [
        '#c23531', '#2f4554', '#61a0a8', '#d48265', '#91c7ae',
        '#749f83', '#ca8622', '#bda29a', '#6e7074', '#546570',
        '#c4ccd3'
      ];
      const index = this.doctors.findIndex(doc => doc.doctor_name === doctorName);
      return colors[index % colors.length];
    }
  }
};
</script>

<style scoped>
#schedule-chart {
  width: 100%;
  height: 400px;
  margin-top: 20px;
}
</style>
